<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>摄像头监控系统</title>
    <link rel="icon" type="image/png" href="/icons/icon.png">
    <style>
        /* 全局样式 */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: #000;
            color: #0ff;
            min-height: 100vh;
        }

        /* 登录页面样式 */
        .login-container {
            width: 100%;
            max-width: 400px;
            padding: 20px;
            margin: 100px auto;
        }

        .login-form {
            background: #001;
            border-radius: 15px;
            padding: 30px;
            box-shadow: 0 0 20px #0ff;
            text-align: center;
            border: 1px solid #0ff;
        }

        .login-form h1 {
            color: #0ff;
            margin-bottom: 10px;
            font-size: 24px;
            text-shadow: 0 0 10px #0ff;
        }

        .login-form h2 {
            color: #0cc;
            margin-bottom: 25px;
            font-size: 18px;
        }

        .input-group {
            margin-bottom: 25px;
            text-align: left;
        }

        .input-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
        }

        .input-group input {
            width: 100%;
            padding: 15px;
            border: none;
            border-radius: 8px;
            background: #002;
            color: #0ff;
            font-size: 16px;
            border: 1px solid #0aa;
        }

        .input-group input:focus {
            outline: none;
            background: #003;
            box-shadow: 0 0 10px #0ff;
        }

        .input-group input::placeholder {
            color: #088;
        }

        .btn-login {
            width: 100%;
            padding: 15px;
            border: none;
            border-radius: 8px;
            background: #003;
            color: #0ff;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            border: 1px solid #0aa;
            text-shadow: 0 0 5px #0ff;
        }

        .btn-login:hover {
            background: #005;
            box-shadow: 0 0 15px #0ff;
        }

        .alert {
            background: #003;
            border: 1px solid #f00;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 20px;
        }

        .alert p {
            color: #f99;
        }

        .footer {
            margin-top: 25px;
            color: #088;
            font-size: 14px;
        }

        /* 监控页面样式 */
        .container {
            width: 100%;
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
            display: none;
        }

        header {
            text-align: center;
            margin-bottom: 30px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 20px;
            background: #001;
            padding: 20px;
            border-radius: 15px;
            border: 1px solid #0aa;
            box-shadow: 0 0 15px #0aa;
        }

        header h1 {
            color: #0ff;
            font-size: 28px;
            text-shadow: 0 0 10px #0ff;
        }

        .status-indicator {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .status-dot {
            width: 15px;
            height: 15px;
            border-radius: 50%;
            background-color: #f00;
            transition: background-color 1s ease;
            box-shadow: 0 0 5px #f00;
        }

        .status-dot.active {
            background-color: #0f0;
            box-shadow: 0 0 10px #0f0;
        }

        .status-text {
            font-weight: 500;
        }

        main {
            margin-bottom: 30px;
        }

        .devices-panel {
            background: #001;
            border-radius: 15px;
            padding: 20px;
            margin-bottom: 30px;
            border: 1px solid #0aa;
            box-shadow: 0 0 15px #0aa;
        }

        .devices-panel h2 {
            color: #0ff;
            margin-bottom: 20px;
            text-align: center;
            text-shadow: 0 0 10px #0ff;
        }

        .device-list {
            display: flex;
            flex-wrap: wrap;
            gap: 15px;
            justify-content: center;
        }

        .device-item {
            background: #002;
            border-radius: 10px;
            padding: 15px;
            border: 1px solid #088;
            cursor: pointer;
            transition: all 0.3s ease;
            min-width: 200px;
        }

        .device-item:hover {
            background: #003;
            box-shadow: 0 0 10px #0aa;
        }

        .device-item.selected {
            background: #004;
            border-color: #0ff;
            box-shadow: 0 0 15px #0ff;
        }

        .device-item h3 {
            color: #0ff;
            margin-bottom: 10px;
        }

        .device-status {
            font-size: 14px;
        }

        .status-idle {
            color: #ff0;
        }

        .status-streaming {
            color: #0f0;
        }

        .video-container {
            background: #001;
            border-radius: 15px;
            overflow: hidden;
            box-shadow: 0 0 20px #0aa;
            margin-bottom: 30px;
            border: 1px solid #0aa;
        }

        .video-feed {
            width: 100%;
            display: block;
            max-height: 70vh;
            object-fit: contain;
        }

        .controls {
            display: flex;
            justify-content: center;
            gap: 20px;
            flex-wrap: wrap;
            margin-bottom: 30px;
        }

        .btn {
            padding: 12px 25px;
            border: none;
            border-radius: 8px;
            background: #003;
            color: #0ff;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            border: 1px solid #0aa;
            text-shadow: 0 0 5px #0ff;
        }

        .btn:hover {
            background: #005;
            box-shadow: 0 0 15px #0ff;
        }

        .btn:disabled {
            background: #002;
            color: #088;
            cursor: not-allowed;
            box-shadow: none;
        }

        .btn-secondary {
            background: #003;
            border: 1px solid #0aa;
        }

        .btn-secondary:hover {
            background: #005;
            box-shadow: 0 0 15px #0ff;
        }

        .btn-danger {
            background: #300;
            border: 1px solid #a00;
        }

        .btn-danger:hover {
            background: #500;
            box-shadow: 0 0 15px #f00;
        }

        .settings-panel {
            background: #001;
            border-radius: 15px;
            padding: 20px;
            margin-top: 20px;
            border: 1px solid #0aa;
            box-shadow: 0 0 15px #0aa;
        }

        .settings-panel h2 {
            color: #0ff;
            margin-bottom: 20px;
            text-align: center;
            text-shadow: 0 0 10px #0ff;
        }

        .settings-group {
            display: flex;
            flex-wrap: wrap;
            gap: 20px;
            justify-content: center;
        }

        .setting-item {
            display: flex;
            flex-direction: column;
            min-width: 150px;
        }

        .setting-item label {
            margin-bottom: 8px;
            color: #0cc;
        }

        .setting-item input[type="range"] {
            width: 100%;
        }

        .setting-item input[type="checkbox"] {
            width: 20px;
            height: 20px;
            margin: 0 auto;
        }

        footer {
            text-align: center;
            color: #088;
            padding: 20px;
            border-top: 1px solid #0aa;
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .container {
                padding: 10px;
            }
            
            header {
                flex-direction: column;
                text-align: center;
            }
            
            header h1 {
                font-size: 24px;
            }
            
            .video-feed {
                max-height: 50vh;
            }
            
            .controls {
                flex-direction: column;
                align-items: center;
            }
            
            .btn {
                width: 80%;
            }
            
            .settings-group {
                flex-direction: column;
                align-items: center;
            }
            
            .device-item {
                width: 100%;
            }
        }
    </style>
</head>
<body>
    <!-- 登录页面 -->
    <div class="login-container" id="loginPage">
        <div class="login-form">
            <h1>摄像头监控系统</h1>
            <h2>🔒 安全访问</h2>
            
            <div id="errorMessage" class="alert" style="display: none;">
                <p id="errorText">密码错误，请重试</p>
            </div>
            
            <form id="loginForm">
                <div class="input-group">
                    <label for="password">请输入访问密码：</label>
                    <input type="password" id="password" name="password" placeholder="输入密码" required>
                </div>
                <button type="submit" class="btn-login">🔓 登录访问</button>
            </form>
            
            <div class="footer">
                <p>© 2025 摄像头监控系统 | 安全访问</p>
            </div>
        </div>
    </div>

    <!-- 监控页面 -->
    <div class="container" id="monitorPage">
        <header>
            <h1>📹 远程摄像头监控</h1>
            <div class="status-indicator">
                <span class="status-dot" id="statusDot"></span>
                <span class="status-text" id="statusText">未选择设备</span>
            </div>
        </header>
        
        <main>
            <!-- 设备列表 -->
            <div class="devices-panel">
                <h2>📱 可用设备</h2>
                <div class="device-list" id="deviceList">
                    <!-- 设备列表将通过JavaScript动态生成 -->
                    <div class="no-devices">暂无可用设备</div>
                </div>
            </div>
            
            <!-- 视频显示区域 -->
            <div class="video-container">
                <img src="" alt="摄像头画面" class="video-feed" id="videoFeed" style="display: none;">
                <div id="noDeviceSelected" style="text-align: center; padding: 50px; color: #088;">
                    请选择一个设备开始视奸
                </div>
            </div>
            
            <!-- 控制按钮 -->
            <div class="controls">
                <button class="btn" id="startBtn" onclick="startCamera()" disabled>▶ 开启摄像头</button>
                <button class="btn btn-danger" id="stopBtn" onclick="stopCamera()" disabled>⏹ 关闭摄像头</button>
                <button class="btn btn-secondary" onclick="playAudio()">🔊 ユ!</button>
                <button class="btn btn-secondary" id="recordBtn" onclick="toggleRecording()">🎤 录音</button>
                <button class="btn btn-secondary" onclick="refreshDevices()">🔄 刷新设备</button>
                <button class="btn btn-secondary" onclick="logout()">🚪 退出登录</button>
            </div>
            
            <!-- 设置面板 -->
            <div class="settings-panel">
                <h2>⚙️ 摄像头设置</h2>
                <div class="settings-group">
                    <div class="setting-item">
                        <label for="flipHorizontal">水平翻转</label>
                        <input type="checkbox" id="flipHorizontal" onchange="debouncedUpdateSettings()">
                    </div>
                    
                    <div class="setting-item">
                        <label for="flipVertical">垂直翻转</label>
                        <input type="checkbox" id="flipVertical" onchange="debouncedUpdateSettings()">
                    </div>
                    
                    <div class="setting-item">
                        <label for="redShift">红色偏移 (-50 to 50)</label>
                        <input type="range" id="redShift" min="-50" max="50" value="0" onchange="debouncedUpdateSettings()">
                    </div>
                    
                    <div class="setting-item">
                        <label for="greenShift">绿色偏移 (-50 to 50)</label>
                        <input type="range" id="greenShift" min="-50" max="50" value="0" onchange="debouncedUpdateSettings()">
                    </div>
                    
                    <div class="setting-item">
                        <label for="blueShift">蓝色偏移 (-50 to 50)</label>
                        <input type="range" id="blueShift" min="-50" max="50" value="0" onchange="debouncedUpdateSettings()">
                    </div>
                </div>
                
                <h2 style="margin-top: 20px;">🎨 色彩校正</h2>
                <div class="settings-group">
                    <div class="setting-item">
                        <label for="redGain">红色增益 (0.5-2.0)</label>
                        <input type="range" id="redGain" min="5" max="20" value="10" onchange="debouncedUpdateColorCorrection()">
                    </div>
                    
                    <div class="setting-item">
                        <label for="greenGain">绿色增益 (0.5-2.0)</label>
                        <input type="range" id="greenGain" min="5" max="20" value="10" onchange="debouncedUpdateColorCorrection()">
                    </div>
                    
                    <div class="setting-item">
                        <label for="blueGain">蓝色增益 (0.5-2.0)</label>
                        <input type="range" id="blueGain" min="5" max="20" value="8" onchange="updateColorCorrection()">
                    </div>
                </div>
            </div>
        </main>
        
        <footer>
            <p>实时监控系统 | 多设备支持 | 按需推流 | 延迟约 0.5~1 秒</p>
        </footer>
    </div>

    <script>
        // 全局变量
        let currentDevice = null;
        let devices = {};
        let refreshInterval = null;
        
        // 录音相关变量
        let mediaRecorder;
        let audioChunks = [];
        let isRecording = false;
        
        // 页面切换函数
        function showMonitorPage() {
            document.getElementById('loginPage').style.display = 'none';
            document.getElementById('monitorPage').style.display = 'block';
            startDeviceRefresh();
        }

        function showLoginPage() {
            document.getElementById('loginPage').style.display = 'block';
            document.getElementById('monitorPage').style.display = 'none';
            stopDeviceRefresh();
        }
        
        // 设备刷新功能
        function startDeviceRefresh() {
            refreshDevices();
            refreshInterval = setInterval(refreshDevices, 5000); // 每5秒刷新一次
        }
        
        function stopDeviceRefresh() {
            if (refreshInterval) {
                clearInterval(refreshInterval);
                refreshInterval = null;
            }
        }
        
        function refreshDevices() {
            fetch('/get_devices')
                .then(response => response.json())
                .then(data => {
                    devices = data;
                    updateDeviceList();
                })
                .catch(error => {
                    console.error('获取设备列表失败:', error);
                });
        }
        
        function updateDeviceList() {
            const deviceList = document.getElementById('deviceList');
            deviceList.innerHTML = '';
            
            if (Object.keys(devices).length === 0) {
                deviceList.innerHTML = '<div class="no-devices">暂无可用设备</div>';
                return;
            }
            
            for (const deviceId in devices) {
                const device = devices[deviceId];
                const deviceElement = document.createElement('div');
                deviceElement.className = 'device-item';
                deviceElement.dataset.deviceId = deviceId;
                
                // 设置设备状态显示
                let statusText = '未知';
                let statusClass = '';
                if (device.status === 'streaming') {
                    statusText = '推流中';
                    statusClass = 'streaming';
                } else if (device.status === 'idle') {
                    statusText = '空闲';
                    statusClass = 'idle';
                }
                
                deviceElement.innerHTML = `
                    <div class="device-info">
                        <div class="device-name">${device.name}</div>
                        <div class="device-status ${statusClass}">${statusText}</div>
                    </div>
                `;
                
                deviceElement.onclick = () => selectDevice(deviceId);
                deviceList.appendChild(deviceElement);
            }
            
            // 如果当前选中的设备存在，更新其按钮状态
            if (currentDevice && devices[currentDevice]) {
                updateControlButtons();
            }
        }
        
        function selectDevice(deviceId) {
            // 移除所有设备项的选中状态
            document.querySelectorAll('.device-item').forEach(item => {
                item.classList.remove('selected');
            });
            
            // 添加选中状态到当前设备
            const selectedElement = document.querySelector(`.device-item[data-device-id="${deviceId}"]`);
            if (selectedElement) {
                selectedElement.classList.add('selected');
            }
            
            // 更新当前设备
            currentDevice = deviceId;
            
            // 更新状态显示
            document.getElementById('statusDot').className = 'status-dot';
            document.getElementById('statusText').textContent = `已选择设备: ${devices[deviceId].name}`;
            
            // 显示视频区域
            document.getElementById('videoFeed').style.display = 'block';
            document.getElementById('noDeviceSelected').style.display = 'none';
            
            // 优化视频源设置 - 使用更高效的更新方式
            const videoFeed = document.getElementById('videoFeed');
            const currentSrc = videoFeed.src;
            const newSrc = `/stream/${deviceId}?t=${Date.now()}`; // 添加时间戳防止缓存
            
            // 只有在src改变时才重新赋值
            if (currentSrc !== newSrc) {
                videoFeed.src = newSrc;
            }
            
            // 更新按钮状态
            updateControlButtons();
        }
        
        function updateControlButtons() {
            const startBtn = document.getElementById('startBtn');
            const stopBtn = document.getElementById('stopBtn');
            
            if (!currentDevice) {
                startBtn.disabled = true;
                stopBtn.disabled = true;
                return;
            }
            
            // 确保从最新设备数据中获取状态
            const device = devices[currentDevice];
            console.log('设备状态更新:', currentDevice, device); // 添加调试日志
            if (device && device.status === 'streaming') {
                startBtn.disabled = true;
                stopBtn.disabled = false;
            } else {
                startBtn.disabled = false;
                stopBtn.disabled = true;
            }
        }

        // 退出登录
        function logout() {
            // 如果正在推流，先停止
            if (currentDevice && devices[currentDevice] && devices[currentDevice].status === 'streaming') {
                stopCamera();
            }
            showLoginPage();
        }

        // 处理登录表单提交
        document.getElementById('loginForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            const password = document.getElementById('password').value;
            const errorMessage = document.getElementById('errorMessage');
            
            // 发送请求到后端验证密码
            fetch('/verify_password', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({password: password})
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showMonitorPage();
                } else {
                    document.getElementById('errorText').textContent = '密码错误，请重试';
                    errorMessage.style.display = 'block';
                    
                    // 3秒后隐藏错误消息
                    setTimeout(function() {
                        errorMessage.style.display = 'none';
                    }, 3000);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                document.getElementById('errorText').textContent = '网络错误，请重试';
                errorMessage.style.display = 'block';
                
                // 3秒后隐藏错误消息
                setTimeout(function() {
                    errorMessage.style.display = 'none';
                }, 3000);
            });
        });

        // 控制摄像头
        function startCamera() {
            if (!currentDevice) {
                alert('请先选择一个设备');
                return;
            }
            
            fetch('/control_camera', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    command: 'start',
                    device_id: currentDevice
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    devices[currentDevice].status = 'streaming';
                    updateDeviceList();
                    updateControlButtons();
                    document.getElementById('statusText').textContent = `设备 ${devices[currentDevice].name} 推流中`;
                    document.getElementById('statusDot').className = 'status-dot active';
                } else {
                    alert('开启摄像头失败: ' + (data.error || '未知错误'));
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('网络错误，无法开启摄像头');
            });
        }

        function stopCamera() {
            if (!currentDevice) {
                alert('请先选择一个设备');
                return;
            }
            
            fetch('/control_camera', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    command: 'stop',
                    device_id: currentDevice
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    devices[currentDevice].status = 'idle';
                    updateDeviceList();
                    updateControlButtons();
                    document.getElementById('statusText').textContent = `设备 ${devices[currentDevice].name} 已停止`;
                    document.getElementById('statusDot').className = 'status-dot';
                } else {
                    alert('停止摄像头失败: ' + (data.error || '未知错误'));
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('网络错误，无法停止摄像头');
            });
        }

        // 更新设置
        function updateSettings() {
            if (!currentDevice) {
                return;
            }
            
            const settings = {
                flip_horizontal: document.getElementById('flipHorizontal').checked,
                flip_vertical: document.getElementById('flipVertical').checked,
                red_shift: parseInt(document.getElementById('redShift').value),
                green_shift: parseInt(document.getElementById('greenShift').value),
                blue_shift: parseInt(document.getElementById('blueShift').value)
            };
            
            fetch('/control_camera', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    command: 'update_settings',
                    device_id: currentDevice,
                    settings: settings
                })
            })
            .then(response => response.json())
            .then(data => {
                if (!data.success) {
                    console.error('更新设置失败:', data.error);
                }
            })
            .catch(error => {
                console.error('Error:', error);
            });
        }
        
        // 更新色彩校正
        function updateColorCorrection() {
            if (!currentDevice) {
                return;
            }
            
            const color_correction = {
                red_gain: parseFloat(document.getElementById('redGain').value) / 10,
                green_gain: parseFloat(document.getElementById('greenGain').value) / 10,
                blue_gain: parseFloat(document.getElementById('blueGain').value) / 10
            };
            
            fetch('/control_camera', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    command: 'update_color_correction',
                    device_id: currentDevice,
                    color_correction: color_correction
                })
            })
            .then(response => response.json())
            .then(data => {
                if (!data.success) {
                    console.error('更新色彩校正失败:', data.error);
                }
            })
            .catch(error => {
                console.error('Error:', error);
            });
        }

        // 页面加载完成后的初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 定期检查设备状态，从1000ms增加到2000ms
            setInterval(() => {
                if (currentDevice && devices[currentDevice]) {
                    // 更新按钮状态
                    updateControlButtons();
                }
            }, 2000);
        });

        // 添加页面可见性变化监听器
        document.addEventListener('visibilitychange', function() {
            // 如果页面不可见且当前有设备正在推流，则自动停止摄像头
            if (document.hidden && currentDevice && devices[currentDevice] && devices[currentDevice].status === 'streaming') {
                console.log('页面失焦，自动停止摄像头');
                stopCamera();
            }
        });

        // 添加窗口失去焦点监听器（作为额外保障）
        window.addEventListener('blur', function() {
            // 如果窗口失去焦点且当前有设备正在推流，则自动停止摄像头
            if (currentDevice && devices[currentDevice] && devices[currentDevice].status === 'streaming') {
                console.log('窗口失去焦点，自动停止摄像头');
                stopCamera();
            }
        });

        // 播放音频
        function playAudio() {
            if (!currentDevice) {
                alert('请先选择一个设备');
                return;
            }
            
            fetch('/control_camera', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    command: 'play_audio',
                    device_id: currentDevice
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    console.log('音频播放指令已发送');
                } else {
                    alert('播放音频失败: ' + (data.error || '未知错误'));
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('网络错误，无法播放音频');
            });
        }
        
        // 切换录音状态
        function toggleRecording() {
            const recordBtn = document.getElementById('recordBtn');
            
            if (!isRecording) {
                // 开始录音
                navigator.mediaDevices.getUserMedia({ audio: true })
                    .then(stream => {
                        // 使用audio/webm格式而不是默认的audio/mpeg
                        const options = { mimeType: 'audio/webm' };
                        mediaRecorder = new MediaRecorder(stream, options);
                        audioChunks = [];
                        
                        mediaRecorder.ondataavailable = event => {
                            audioChunks.push(event.data);
                        };
                        
                        mediaRecorder.onstop = () => {
                            // 创建音频文件并发送到服务端
                            const audioBlob = new Blob(audioChunks, { type: 'audio/webm' });
                            uploadAudioFile(audioBlob);
                            
                            // 停止所有音轨以释放麦克风
                            stream.getTracks().forEach(track => track.stop());
                        };
                        
                        mediaRecorder.start();
                        isRecording = true;
                        recordBtn.textContent = '⏹ 停止录音';
                        recordBtn.style.background = '#300';
                        console.log('开始录音...');
                    })
                    .catch(error => {
                        console.error('无法访问麦克风:', error);
                        alert('无法访问麦克风，请检查权限设置');
                    });
            } else {
                // 停止录音
                if (mediaRecorder && mediaRecorder.state !== 'inactive') {
                    mediaRecorder.stop();
                }
                isRecording = false;
                recordBtn.textContent = '🎤 录音';
                recordBtn.style.background = '';
                console.log('录音已保存');
            }
        }
        
        // 上传音频文件到服务端
        function uploadAudioFile(audioBlob) {
            const formData = new FormData();
            formData.append('audio', audioBlob, 'recorded_audio.mp3');
            formData.append('device_id', currentDevice); // 添加设备ID
            
            fetch('/upload_audio', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    console.log('音频文件已上传到设备');
                    // 播放刚录制的音频
                    playRecordedAudio();
                } else {
                    alert('上传音频失败: ' + (data.error || '未知错误'));
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('网络错误，无法上传音频');
            });
        }
        
        // 播放刚录制的音频
        function playRecordedAudio() {
            fetch('/control_camera', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    command: 'play_recorded_audio',
                    device_id: currentDevice
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    console.log('录制的音频播放指令已发送');
                } else {
                    alert('播放录制音频失败: ' + (data.error || '未知错误'));
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('网络错误，无法播放录制的音频');
            });
        }
        
        // 防抖函数，避免频繁操作
        function debounce(func, wait) {
            let timeout;
            return function executedFunction(...args) {
                const later = () => {
                    clearTimeout(timeout);
                    func(...args);
                };
                clearTimeout(timeout);
                timeout = setTimeout(later, wait);
            };
        }
        
        // 优化后的设置更新函数，增加防抖延迟到150ms
        const debouncedUpdateSettings = debounce(updateSettings, 150);
        const debouncedUpdateColorCorrection = debounce(updateColorCorrection, 150);

    </script>
</body>
</html>